//
//  HJVersionUpdate.m
//  KaiChat
//
//  Created by lx on 2023/10/19.
//

#import "HJVersionUpdate.h"
#import "HJMinePresent.h"
#import "QMUIButton.h"

@interface HJVersionUpdate ()

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, strong) NSDictionary *info;
@property (nonatomic, weak) QMUIButton *dismissButton;

@end

@implementation HJVersionUpdate


- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIButton *maskView = [[UIButton alloc] initWithFrame:self.view.bounds].addTo(self.view);
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    _maskView = maskView;
    
    NSString *updateContent = _info[@"desc"];
    
    
    NSAttributedString *attributedText = [updateContent titleMargin:3 font:UIFontMake(12) alignment:NSTextAlignmentCenter];
    CGRect textLabelRect = [attributedText boundingRectWithSize:CGSizeMake(290, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    
    
    CGFloat contentViewH = 315 + textLabelRect.size.height;
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.frame = CGRectMake((KScreenWidth - 290) * 0.5, -contentViewH, 290, contentViewH);
    contentView.backgroundColor = UIColor.clearColor;
    _contentView = contentView;

    UIImageView *topImageView = [UIImageView addToView:contentView];
    topImageView.image = [UIImage imageNamed:@"versionUpdate"];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(180);
    }];
    
    UIView *updateContentView = [UIView addToView:contentView];
    updateContentView.backgroundColor = UIColor.tj_backgroundColor;
    updateContentView.frame = CGRectMake(0, 0, contentView.tj_width, contentViewH - 180);
    [updateContentView addRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight radius:10];
    [updateContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(topImageView.mas_bottom).offset(-2);
    }];
    
    QMUIButton *dismissButton = [QMUIButton addToView:maskView];
    [dismissButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [dismissButton setImage:[UIImage imageNamed:@"update_close"] forState:UIControlStateNormal];
    [dismissButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contentView.mas_bottom);
        make.width.height.offset(44);
        make.centerX.offset(0);
     }];

    UILabel *titleLabel = [UILabel lableWithSuperView:updateContentView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:_info[@"title"] textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(6);
        make.left.offset(leftRightMargin);
    }];
 
    UILabel *contentLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_868391Color title:updateContent textAlignment:NSTextAlignmentLeft];
    contentLabel.numberOfLines = 0;
    contentLabel.attributedText = [contentLabel.text titleMargin:3 alignment:NSTextAlignmentLeft];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(10);
        make.left.offset(20);
        make.width.offset(contentView.tj_width - 40);
        make.height.mas_greaterThanOrEqualTo(40);
    }];
    
    HJStyle1Button *updateButton = [HJStyle1Button buttonWithSuperView:updateContentView font:UIFontMediumMake(14) color:nil title:@"Upgrade"];
    updateButton.addCornerRadius(10);
    updateButton.backgroundColor = UIColor.tj_mainColor;
    [updateButton addTarget:self action:@selector(didClickUpdateButton) forControlEvents:UIControlEventTouchUpInside];
    [updateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(20);
        make.height.offset(40);
        make.left.right.inset(20);
        
    }];
    _dismissButton = dismissButton;
    
    self.contentView.tj_centerY = self.view.tj_centerY - 30;
    
    NSInteger way = [_info[@"way"] intValue];
    if (way == 2) {
        dismissButton.hidden = YES;
    }
    
}

- (void)didClickDismissButton {
    [self dismissComplete:nil];
}

- (void)didClickUpdateButton {
    NSString *download_url = _info[@"url"];
    download_url = [download_url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([download_url length]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:download_url] options:@{} completionHandler:nil];
    }
    
}

+ (void)checkVersionUpdateInController:(UIViewController *)controller {
    
    [HJMinePresent loadVersionInfoComplete:^(NSDictionary * _Nullable data, NSError * _Nullable error) {
        
        if (error) return;
        if (![data isKindOfClass:NSDictionary.class]) return;
        
        NSString *currentVersion = getAppVersion();

        HJUserInfo.showUpdateDate = [NSString stringWithFormat:@"%.f", NSDate.date.timeIntervalSince1970];

        NSString *serverVersion = toString(data[@"version_no"]);
        if (compareNumberValue(serverVersion, currentVersion) == NSOrderedDescending) {
            if (HJTools.tool.versionUpdate) {
                return;
            }
            HJVersionUpdate *versionUpdate = [[HJVersionUpdate alloc] init];
            versionUpdate.info = data;
            [controller presentViewController:versionUpdate animated:NO completion:nil];
            HJTools.tool.versionUpdate = versionUpdate;
        }
    }];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    } completion:^(BOOL finished) {
        
    }];
    
}

- (void)dismissComplete:(void (^)(void))complete {
    
    [UIView animateWithDuration:0.05 animations:^{
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.contentView.alpha = 0;
        self.dismissButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) {
                complete();
            }
        }];
    }];
}

- (void)dealloc {
    HJTools.tool.versionUpdate = nil;
}


@end

